package com.xjx.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.xjx.constant.MessageConstant;
import com.xjx.constant.RedisConstant;
import com.xjx.constant.RedisMessageConstant;
import com.xjx.entity.Result;
import com.xjx.pojo.Order;
import com.xjx.service.OrderService;
import com.xjx.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @Version v1.0
 * @ClassName:
 * @Description:
 * @Author:xjx
 */
//体检预约处理
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;

    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        //从Redis中获取缓存的验证码，key为手机号+RedisConstant.SENDTYPE_ORDER
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        //校验手机验证码
        if (validateCodeInRedis != null && validateCode != null & validateCode.equals(validateCodeInRedis)) {
            //比对成功，调用体检预约服务
            map.put("orderType", Order.ORDERTYPE_WEIXIN);//设置预约方式
            Result result = null;
            try {
                result = orderService.order(map);//通过Dubbo来远程调用服务来实现在线预约业务处理

            } catch (Exception e) {
                e.printStackTrace();
                return result;
            }
            if (result.isFlag()) {
                //预约成功，可以给用户发送短信
                try {
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, (String) map.get("orderDate"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
        //比对不成功，返回页面
        else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }

    //根据预约id查询预约相关信息
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        //map最灵活，在service层进行封装想要的数据
        try {
            Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }

    }
}
